package com.oddfar.campus.business.service.Impl;

import com.oddfar.campus.common.domain.PageResult;
import com.oddfar.campus.common.exception.ServiceException;
import com.oddfar.campus.common.utils.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.sql.Date;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.oddfar.campus.business.mapper.ClqkxxMapper;
import com.oddfar.campus.business.domain.Clqkxx;
import com.oddfar.campus.business.service.ClqkxxService;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ClqkxxServiceImpl extends ServiceImpl<ClqkxxMapper, Clqkxx> implements ClqkxxService{
    @Autowired
    private ClqkxxMapper clqkxxMapper;

    @Override
    public PageResult<Clqkxx> page(Clqkxx clqkxx) {
        Long userId = SecurityUtils.getUserId();
        if (userId != 1) {
            return clqkxxMapper.selectPage(clqkxx, userId);
        }
        return clqkxxMapper.selectPage(clqkxx);
    }

    @Override
    public PageResult<Clqkxx> page_id(Clqkxx clqkxx) {
        return clqkxxMapper.selectPage_id(clqkxx);
    }

    @Override
    @Transactional
    public int insertClqkxx(Clqkxx clqkxx) {
        clqkxx.setDelFlag(false);
        clqkxx.setCreateUser(SecurityUtils.getUserId());
        clqkxx.setCreateTime(getNowTime());
        try {
            if (clqkxx.getUserId() == null || clqkxx.getUserId().toString().length() < 1) {
                long userId = clqkxxMapper.selectIDbyMobile(clqkxx.getPhonenumber());
                clqkxx.setUserId(userId);
            }
        } catch (Exception e) {
            throw new ServiceException("新增车辆失败：未找到" + clqkxx.getPhonenumber() + "该手机号对应的用户ID，请先添加用户信息");
        }
        checkIsFirstPlate(clqkxx.getPhonenumber(),clqkxx.getClpzh());
        return clqkxxMapper.insert(clqkxx);
    }

    @Override
    public int updateClqkxx(Clqkxx clqkxx) {
        return clqkxxMapper.updateById(clqkxx);
    }


    public java.sql.Date getNowTime() { //获取当前时间
        long time = System.currentTimeMillis();
        return new Date(time);
    }

    public void checkIsFirstPlate(String phonenumber,String clpzh) {
        clqkxxMapper.checkIsFirstPlate(phonenumber,clpzh);
    }
}
